//
//  WCTLogService.m
//  WeChatTool
//
//  Created by TerryChe on 2017/1/12.
//  Copyright © 2017年 TerryChe. All rights reserved.
//

#import "WCTLogService.h"
#import "WCTConfig.h"
//#import "BuglyHeader/Bugly.h"

@implementation WCTLogService

/**
 *  单例模式，
 *
 *  @return WCTLogService
 */
+(instancetype)sharedInstance{
    static WCTLogService *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

-(void)writeLog:(NSString *)log{
    NSLog(@"%@", log);
    
//    [BuglyLog level:BuglyLogLevelDebug log:@"%@", log];
    
    NSString *path = [str_wct_dir stringByAppendingPathComponent:str_wct_log];
    
    NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:path];
    //默认是从开始位置写，所以我们需要将写入游标设置到尾部
    //从文件的末尾写入
    [handle seekToEndOfFile];
    
    NSData *data = [self createMsg:log];
    
    [handle writeData:data];
    
    [handle synchronizeFile];
    
    //关闭文件
    [handle closeFile];
}

-(void)cleanLog{
    NSLog(@"CleanLog");
    
    NSString *path = [str_wct_dir stringByAppendingPathComponent:str_wct_log];
    
    NSData *data = [self createMsg:@"CleanLog"];
    
    [data writeToFile:path atomically:YES];
}

-(NSData *)createMsg:(NSString *)msg{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8 * 60 * 60]];//+8小时
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *dateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    NSString *str = [NSString stringWithFormat:@"%@ %@\r\n", dateStr, msg];
    return [str dataUsingEncoding:NSUTF8StringEncoding];
}

@end
